<?php
namespace ImiApp\Module\IM\WebSocketController;

use Imi\Server\Server;
use Imi\RequestContext;
use Imi\Aop\Annotation\Inject;
use ImiApp\Module\IM\Enum\MessageType;
use Imi\Controller\WebSocketController;
use ImiApp\Module\IM\Enum\MessageActions;
use Imi\Server\Route\Annotation\WebSocket\WSRoute;
use Imi\Server\Route\Annotation\WebSocket\WSAction;
use Imi\Server\Route\Annotation\WebSocket\WSController;

// use Imi\Server\Route\Annotation\WebSocket\WSConfig;

use Imi\ConnectContext;
use ImiApp\Module\Member\Service\TeamService;
use Imi\Db\Db;

/**
 * IM 控制器
 * @WSController(route="/im")
 */
class IMController extends WebSocketController
{
    /**
     * 加入系统房间
     *
     * @WSAction
     * @WSRoute({"action"="im.joinSysRoom"})
     * 
     * @param array $data
     * @return void
     */
    public function joinSysRoom($data)
    {

        // var_dump('{"action":"im.joinSysRoom"}');
        if(!isset($data['uid'])){//区域id
            $data['uid'] = 'uid';
        }
        $group = 'im.sysroom.' . $data['uid'];
        $this->server->joinGroup($group, $this->frame->getFd());
        // var_dump($group,RequestContext::getBean('MemberSessionService'));
        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');

        // Server::sendToGroup($group, [
        //     'action'    =>  MessageActions::IM_RECEIVE,
        //     'sender'    =>  '系统消息',
        //     'type'      =>  MessageType::SYSTEM,
        //     'content'   =>  $memberSession->getMemberInfo()->username . ' 上线了',
        //     'time'      =>  date('Y-m-d H:i:s'),
        // ]);


        $GroupObj = $this->server->getGroup($group);//获取组对象
        $num = $this->server->getGroup($group)->count();
        var_dump('num',$num);

        $list = $this->server->getGroup($group)->getFds();
        var_dump('list',$list);


        // var_dump('groupName',$GroupObj->getFds());
        return [
            'action'    =>  MessageActions::IM_JOIN_SYS_ROOM,
            'msg'       =>  'ok',
            'code'     => 1,
        ];
    }









    /**
     * 加入班级房间
     *
     * @WSAction
     * @WSRoute({"action"="im.joinTeamRoom"})
     * 
     * @param array $data
     * @return void
     */
    public function joinTeamRoom($data)
    {

        
        if(!isset($data['team_id'])){//班级id
            return [
                'action'    =>  'joinTeamRoom',//推送班级
                'msg'       =>  '需要班级id',
                'code'     => -1,
            ];
        }     
        
        $group = 'im.room.team' . $data['team_id'];//班级组

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();
        //判断该用户是否是学生，如果是学生 判断是否在该班级
        if($user->group_id==4){
            $team =   new TeamService;

            //不在该班级的学生不能加入
            if(!$team->getUid_is_team($user->id,$data['team_id'])){
                return [
                    'action'    =>  MessageActions::IM_JOIN_SYS_ROOM,
                    'msg'       =>  '不在该班级里面',
                    'code'     => -1,
                ];
            }

        }else{
            var_dump('角色组：',$user->group_id);
        }

        $this->server->joinGroup($group, $this->frame->getFd());

        Server::sendToGroup($group, [
            'action'    =>  MessageActions::IM_RECEIVE,
            'sender'    =>  '班级消息',
            'type'      =>  MessageType::TEAM,
            'content'   =>  $user->username . ' 进入班级',
            'time'      =>  date('Y-m-d H:i:s'),
        ]);


        $GroupObj = $this->server->getGroup($group);//获取组对象
        $num = $this->server->getGroup($group)->count();
        var_dump('num',$num);

        $list = $this->server->getGroup($group)->getFds();
        var_dump('list',$list);


        // var_dump('groupName',$GroupObj->getFds());
        return [
            'action'    =>  MessageActions::IM_JOIN_SYS_ROOM,
            'msg'       =>  'ok',
            'code'     => 1,
        ];
    }


    /**
     * 发送班级消息
     *
     * @WSAction
     * @WSRoute({"action"="im.sendTeamMsg"})
     * 
     * @param array $data
     * @return void
     */
    public function sendTeamMsg($data)
    {   
        if(!isset($data['team_id'])){//班级id
            return [
                'action'    =>  'sendTeamMsg',//推送班级
                'msg'       =>  '需要班级id',
                'code'     => -1,
            ];
        }   
        $group = 'im.room.team' . $data['team_id'];//班级组

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();
        //判断该用户是否是学生，如果是学生 判断是否在该班级
        if($user->group_id==4){
            $team =   new TeamService;

            //不在该班级的学生不能加入
            if(!$team->getUid_is_team($user->id,$data['team_id'])){
                return [
                    'action'    =>  MessageActions::IM_JOIN_SYS_ROOM,
                    'msg'       =>  '不在该班级里面',
                    'code'     => -1,
                ];
            }

        }else{
            var_dump('sendTeamMsg角色组：',$user->group_id);
        }

        $this->server->joinGroup($group, $this->frame->getFd());
        


        $db = Db::query();
        $indata['time'] = time();

        $indata['send_uid'] = $user->id;
        $indata['send_time'] = time();
        $indata['team_id'] = $data['team_id'];
        $indata['content'] = $data['content'];

        $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
        $indata['ip'] = $clientInfo['remote_ip'];
        $db->table('sc_chat_team')->insert($indata);


        Server::sendToGroup($group, [
            'action'    =>  MessageActions::IM_RECEIVE,
            'username'    =>  $user->username,
            'send_id'   =>  $user->id,
            'type'      =>  MessageType::TEAM,
            'content'   =>  $data['content'],
            'time'      =>  date('Y-m-d H:i:s'),
        ]);


    }


    





    
    /**
     * 给某个人发送消息
     *
     * @WSAction
     * @WSRoute({"action"="im.sendUserMsg"})
     * 
     * @param array $data
     * @return void
     */
    public function sendUserMsg($data)
    {   
   
        //组，请从这里开始修改 ⌚0325

         /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
         $memberSession = RequestContext::getBean('MemberSessionService');
         $user = $memberSession->getMemberInfo();

        if(isset($data['type'])){
            $type = $data['type'];
        }else{
            $type = 1;
        }

        var_dump('普通消息_____________________');
        var_dump($data);

        if($type!=7){
            if($user->id > $data['re_uid']){
                $group = 'im.room.user' . $user->id.'_'.$data['re_uid'];
            }else{
                $group = 'im.room.user' . $data['re_uid'].'_'.$user->id;
            }
            $this->server->joinGroup($group, $this->frame->getFd());
        }



      
        
        // var_dump('data',$data,$type);
        if($type==7){

            //消息已读
            $this->msg_status_Read($data['msg_id']);
            var_dump($data);
            return null;
        }elseif($type==1){
             
            

            
 
            // $this->server->joinGroup('im.sysroom.'.$user->id, $this->frame->getFd());

            $db = Db::query();
            $indata['time'] = time();

            $indata['send_uid'] = $user->id;
            $indata['send_time'] = time();
            $indata['re_uid'] = $data['re_uid'];
            $indata['content'] = $data['content'];
            $indata['group'] = $group;
            $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
            $indata['ip'] = $clientInfo['remote_ip'];
            $res = $db->table('sc_chat')->insert($indata);






        





            Server::sendToGroup($group, [
                'action'    =>  'chat',
                'username'    =>  $user->username,
                'send_uid'   =>  $user->id,
                'msg_id'    => $res->getLastInsertId(),
                'type'      =>  MessageType::STUDENT,
                'content'   =>  $data['content'],
                'time'      =>  date('Y-m-d H:i:s'),
            ]);

            //给这个人发送系统消息
            Server::sendToGroup('im.sysroom.'.$data['re_uid'], [
                'action'    =>  'sys',
                'username'    =>  $user->username,
                'send_uid'   =>  $user->id,
                'msg_id'    => $res->getLastInsertId(),
                'type'      =>  '1',//类型:1=普通聊天消息,2=心跳,3=订单号,4=系统消息,5=未知,6=未知,7=消息已读,10=语音,11=图片,12=文件
                'content'   =>  $data['content'],
                'time'      =>  date('Y-m-d H:i:s'),
            ]);
        }

    }


    /**
     * 消息已读
     *
     * @param int $id
     * @return void
     */
    public function msg_status_Read($id)
    {
        var_dump('在线已阅读ID:'.$id);
        $db = Db::query();
        $res = $db->table('sc_chat')->where('id','=',$id)->update(['msg_status'=>2]);
        //取消定时发送模版


    }

    
    /**
     * 消息已读
     *
     * @param int $id
     * @return void
     */
    public function msg_status_Read2($id)
    {
        var_dump('jigou在线已阅读ID:'.$id);
        $db = Db::query();
        $res = $db->table('sc_chat_jigou')->where('id','=',$id)->update(['msg_status'=>2]);
        //取消定时发送模版

    }    





    /**
     * 给某个人发送消息
     *
     * @WSAction
     * @WSRoute({"action"="im.sendAskUserMsg"})
     * 
     * @param array $data
     * @return void
     */
    public function sendAskUserMsg($data)
    {   
   
       

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();

        var_dump('382Ask_____________________');
        var_dump($data);


        if(isset($data['type'])){
            $type = $data['type'];
        }else{
            $type = 1;
        }
        

        if($type!=7){
            if($user->id > $data['re_uid']){
                $group = 'im.room.user.sys' . $user->id.'_'.$data['re_uid'];
            }else{
                $group = 'im.room.user.sys' . $data['re_uid'].'_'.$user->id;
            }
            var_dump('group_sendAskUserMsg',$group);
            $this->server->joinGroup($group, $this->frame->getFd());
        }





        // var_dump('data',$data,$type);
        if($type==7){
            //消息已读
            $this->msg_status_Read2($data['msg_id']);
            return null;
        }elseif($type==1){
             


            // $this->server->joinGroup('im.sysroom.'.$user->id, $this->frame->getFd());

            $db = Db::query();
            $indata['time'] = time();


            $indata['send_uid'] = $user->id;
            $indata['send_time'] = time();
            $indata['re_uid'] = $data['re_uid'];
            $indata['content'] = $data['content'];
            $indata['admin_id'] = $data['admin_id'];
            $indata['group'] = $group;
            $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
            $indata['ip'] = $clientInfo['remote_ip'];
            $res  = $db->table('sc_chat_jigou')->insert($indata);





            Server::sendToGroup($group, [
                'action'    =>  'chat',
                'username'    =>  $user->username,
                'send_uid'   =>  $user->id,
                'type'      =>  MessageType::STUDENT,
                'msg_id'    => $res->getLastInsertId(),
                'admin_id' => $data['admin_id'],
                'content'   =>  $data['content'],
                'time'      =>  date('Y-m-d H:i:s'),
            ]);


            
            //给这个人发送系统消息
            Server::sendToGroup('im.sysroom.'.$data['re_uid'], [
                'action'    =>  'sys',
                'username'    =>  $user->username,
                'send_uid'   =>  $user->id,
                'msg_id'    => $res->getLastInsertId(),
                'type'      =>  '1',//类型:1=普通聊天消息,2=心跳,3=订单号,4=系统消息,5=未知,6=未知,7=消息已读,10=语音,11=图片,12=文件
                'content'   =>  $data['content'],
                'time'      =>  date('Y-m-d H:i:s'),
            ]);

        }


    }


    
    /**
     * 加入某个人的消息
     *
     * @WSAction
     * @WSRoute({"action"="im.joinUserMsg"})
     * 
     * @param array $data
     * @return void
     */
    public function joinUserMsg($data)
    {   
   
         /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
         $memberSession = RequestContext::getBean('MemberSessionService');
         $user = $memberSession->getMemberInfo();
       
        if($user->id > $data['re_uid']){
            $group = 'im.room.user' . $user->id.'_'.$data['re_uid'];
        }else{
            $group = 'im.room.user' . $data['re_uid'].'_'.$user->id;
        }
        
        $this->server->joinGroup($group, $this->frame->getFd());
        
        return [
                'action'    =>  'joinUserMsg',
                'msg'       =>  '用户聊天',
                'code'     => 1,
        ];


    }



     /**
     * 推送内容
     *
     * @WSAction
     * @WSRoute({"action"="im.push"})
     * 
     * @param array $data
     * @return void
     */
    public function push($data)
    {
        var_dump('im.push',$data);
        $content = $data['content'] ?? '';
        if('' === $content)
        {
            return;
        }
        
        if(mb_strlen($content) > 999)
        {
            $content = mb_substr($content, 0, 999);
        }


        if(!isset($data['roomId'])){//区域id
            $data['roomId'] = 'com';
        }
        $group = 'im.room.' . $data['roomId'];

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();
        

        $GroupObj = $this->server->getGroup($group);//获取组对象
        var_dump($group.'人数:',$GroupObj->count());


        
        

        
        // var_dump('组列表',$this->server->getGroups());
        // var_dump('getGroup',$GroupObj);
        

        if($memberSession->getMemberInfo()->group_id==3){//1老板 2机构 3老师 4学生

            
            $time = date('Y-m-d H:i:s');
            defer(function() use($user, $content, $time, $group){
                Server::sendToGroup( $group, [
                    'action'    =>  MessageActions::IM_RECEIVE,
                    'type'      =>  MessageType::SYSTEM,
                    'sender'    =>  $user->username,
                    'user_id'   =>  $user->id,
                    'content'   =>  $content,
                    'time'      =>  $time,
                ]);
            });
            return [
                'action'    =>  MessageActions::IM_SEND,
            ];



        }else{
            return [
                'action'    =>  MessageActions::IM_SEND,
                'msg'       =>  '非机构！',
                'code'     => -1,
            ];
        }
        


      
    }






    /**
     * 推送班级内容
     *
     * @WSAction
     * @WSRoute({"action"="im.pushteam"})
     * 
     * @param array $data
     * @return void
     */
    public function pushteam($data)
    {
        
        $content = $data['content'] ?? '';
        if('' === $content)
        {
            return;
        }
        


        if(!isset($data['team_id'])){//区域id
            return [
                'action'    =>  'pushteam',//推送班级
                'msg'       =>  '需要班级id',
                'code'     => -1,
            ];
        }

        $group = 'im.room.team' . $data['team_id'];//班级组

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();
        

        $GroupObj = $this->server->getGroup($group);//获取组对象
        var_dump($group.'人数:',$GroupObj->count());
        
        $Fds = $GroupObj->getFds();
        foreach($Fds as $fd){
            $memberId = ConnectContext::get('memberId', null, $fd);//注释
            var_dump('fd'.$fd,'ID:'.$memberId);
        }
        // var_dump('组列表',$this->server->getGroups());
        // var_dump('getGroup',$GroupObj);
        

        if($memberSession->getMemberInfo()->group_id==3){//1老板 2机构 3老师 4学生

            
            $time = date('Y-m-d H:i:s');
            defer(function() use($user, $content, $time, $group){
                Server::sendToGroup( $group, [
                    'action'    =>  MessageActions::IM_RECEIVE,
                    'type'      =>  MessageType::TEAM,
                    'sender'    =>  $user->username,
                    'user_id'   =>  $user->id,
                    'content'   =>  $content,
                    'time'      =>  $time,
                ]);
            });
            return [
                'action'    =>  MessageActions::IM_SEND,
            ];



        }else{
            return [
                'action'    =>  MessageActions::IM_SEND,
                'msg'       =>  '非机构！',
                'code'     => -1,
            ];
        }
        


      
    }







    /**
     * 加入房间
     *
     * @WSAction
     * @WSRoute({"action"="im.joinRoom2"})
     * 
     * @param array $data
     * @return void
     */
    public function joinRoom($data)
    {
        $group = 'im.room.' . $data['roomId'];
        $this->server->joinGroup($group, $this->frame->getFd());
        var_dump($group,RequestContext::getBean('MemberSessionService'));
        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        var_dump($memberSession);
        Server::sendToGroup($group, [
            'action'    =>  MessageActions::IM_RECEIVE,
            'sender'    =>  '系统消息',
            'type'      =>  MessageType::SYSTEM,
            'content'   =>  $memberSession->getMemberInfo()->username . ' 进来了',
            'time'      =>  date('Y-m-d H:i:s'),
        ]);
        return [
            'action'    =>  MessageActions::IM_JOIN_ROOM,
        ];
    }

    /**
     * 发送内容
     *
     * @WSAction
     * @WSRoute({"action"="im.send"})
     * 
     * @param array $data
     * @return void
     */
    public function send($data)
    {
        $content = $data['content'] ?? '';
        if('' === $content)
        {
            return;
        }
        if(mb_strlen($content) > 999)
        {
            $content = mb_substr($content, 0, 999);
        }
        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $sender = $memberSession->getMemberInfo()->username;
        $roomId = $data['roomId'];
        $time = date('Y-m-d H:i:s');
        defer(function() use($sender, $content, $time, $roomId){
            Server::sendToGroup('im.room.' . $roomId, [
                'action'    =>  MessageActions::IM_RECEIVE,
                'type'      =>  MessageType::CHAT,
                'username'    =>  $sender,
                'send_uid'    =>  $memberSession->getMemberInfo()->id,
                'content'   =>  $content,
                'time'      =>  $time,
            ]);
        });
        return [
            'action'    =>  MessageActions::IM_SEND,
        ];
    }


    public function get_msg_type($group_id){
        switch ($group_id) {
            case '1':
                return MessageType::BOSS;
                break;
            case '2':
                return MessageType::JIGOU;
                break;
            case '3':
                return MessageType::TEACHER;
                break;
            case '4':
                return MessageType::STUDENT;
                break;

            case '5':
                return MessageType::AREA;
                break;
            case '6':
                return MessageType::SYSTEM;
                break;
            case '7':
                return MessageType::TEAM;
                break;
            case '8':
                return MessageType::UNREAD;
                break;

            default:
                # code...
                break;
        }
        
    }
    
}
